# include "VertexScalBufferBindAble.h"
# include <DirectXMath.h>
# include "d3d11.h"

VertexScalBufferBindAble::VertexScalBufferBindAble(ID3D11Device* _device, float3 _translation, float3 _scale)
{
	this->m_transform.translation = _translation;
	this->m_transform.scale = _scale;
	DirectX::XMMATRIX matrix = DirectX::XMMatrixScaling(1.0f, 1.0f, 1.0f) * DirectX::XMMatrixTranslation(0.0f, 0.0f, 0.0f);
	D3D11_BUFFER_DESC cbd = {};
	cbd.Usage = D3D11_USAGE_DYNAMIC;
	cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	cbd.ByteWidth = sizeof(matrix);
	cbd.StructureByteStride = 0;

	D3D11_SUBRESOURCE_DATA csd = {};
	
	csd.pSysMem = &matrix;

	_device->CreateBuffer(&cbd, &csd, this->m_vs_constant_buffer.GetAddressOf());
}

void VertexScalBufferBindAble::bind(ID3D11DeviceContext* _context)
{
	_context->VSSetConstantBuffers(0, 1, this->m_vs_constant_buffer.GetAddressOf());
}

void VertexScalBufferBindAble::changeTranslation(ID3D11DeviceContext* _context, float _x, float _y)
{
	this->m_transform.translation.x = _x;
	this->m_transform.translation.y = _y;
	// 在世界中的大小与位置
	DirectX::XMMATRIX size = DirectX::XMMatrixScaling(32.0f / 2.0f, 32.0f / 2.0f, 1.0f);
	DirectX::XMMATRIX pos = DirectX::XMMatrixTranslation(this->m_transform.translation.x + 16.0f, -this->m_transform.translation.y - 16.0f, 0.0f);
	DirectX::XMMATRIX word = size * pos;
	// 视图矩阵
	DirectX::XMMATRIX view_matrix = DirectX::XMMatrixLookAtLH(DirectX::XMVectorSet(0.0f, 0.0f, -1000.0f, 1.0f), // 摄像机位置  
		DirectX::XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f),     // 目标点（世界空间原点）  
		DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)      // 上方向（y轴）);
	);
	// 投影矩阵
	DirectX::XMMATRIX projection_matrix = DirectX::XMMatrixOrthographicLH(2560.0f, 1440.0f, 0.0f, 1000.0f);
	DirectX::XMMATRIX matrix = word * view_matrix * projection_matrix;
	matrix = DirectX::XMMatrixTranspose(matrix);
	D3D11_MAPPED_SUBRESOURCE mapped_resource;
	_context->Map(this->m_vs_constant_buffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource);
	memcpy(mapped_resource.pData, (void*)&matrix, sizeof(matrix));
	_context->Unmap(this->m_vs_constant_buffer.Get(), 0);
}

VertexScalBufferBindAble::~VertexScalBufferBindAble()
{
}
